package com.codeyang.mocktest2.service.impl;

import com.codeyang.mocktest2.service.FileLastingService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;

/**
 * 描述: describe
 *
 * @author shengyang5
 * @version 2021/7/22 10:40
 */
@Service
public class FileLastingServiceImpl implements FileLastingService {

    public static final String UP_LOAD_FILE_PATH = "src/main/resources/upload/";


    @Override
    public String fileWriteLoadContent(MultipartFile file, String newFileName) {
        StringBuilder sb = null;
        try {
            // 处理逻辑 存储上传的文件
            File loadFile = new File(UP_LOAD_FILE_PATH + newFileName);

            sb = new StringBuilder();

            file.transferTo(loadFile);

            // 就拿到文件的内容
            InputStream in = file.getInputStream();

            byte[] b = new byte[1024];
            int len = -1;
            while ((len = in.read(b, 0, b.length)) != -1) {
                String str = new String(b, 0, len, "UTF-8");
                sb.append(str);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sb.toString();
    }
}
